package com.xiaoxu.privatechat.service.common;

import com.xiaoxu.privatechat.bean.PageBean;
import com.xiaoxu.privatechat.dao.common.AccountDao;
import com.xiaoxu.privatechat.dao.common.FriendDao;
import com.xiaoxu.privatechat.entity.common.Account;
import com.xiaoxu.privatechat.entity.common.Friend;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author xiaoxu
 * @description 用户管理service
 * @date 2023/2/13
 */
@Service
public class AccountService {

    @Resource
    private AccountDao accountDao;

    @Resource
    private FriendDao friendDao;

    /**
     * @param id 用户id
     * @return Account
     * @description 根据用户id查询
     */
    public Account find(Long id) {
        return accountDao.find(id);
    }

    /**
     * @param username 用户名
     * @return Account
     * @description 按照用户名查找用户
     */
    public Account findByUsername(String username) {
        return accountDao.findByUsername(username);
    }

    /**
     * @param account 用户信息
     * @return Account
     * @description 用户添加/编辑操作
     */
    public Account save(Account account) {
        return accountDao.saveAndFlush(Objects.requireNonNull(account));
    }

    /**
     * @param account 账户信息
     * @return Account
     * @description 用户注册
     */
    @Transactional
    public Account register(Account account) {
        if (account != null && account.getSex() == Account.USER_SEX_MAN) {
            account.setStatus(Account.ACOUNT_USER_STATUS_ENABLE);
            account.setHeadPic(Account.ACOUNT_CHAT_HEAD_PIC_MAN);
        } else if (account != null && account.getSex() == Account.USER_SEX_WOMAN) {
            account.setStatus(Account.ACOUNT_USER_STATUS_EXAMINE);
            account.setHeadPic(Account.ACOUNT_CHAT_HEAD_PIC_WOMAN);
        } else {
            throw new RuntimeException("错误，性别不在系统字典中");
        }
        Account user = accountDao.save(Objects.requireNonNull(account));
        Account kefu = accountDao.find(1L);
        List<Friend> userFriendList = friendDao.findByAccountId(Objects.requireNonNull(user).getId());
        addFriend(userFriendList, user, kefu);
        //把自己添加到对方通讯录
        List<Friend> kefuFriendList = friendDao.findByAccountId(kefu.getId());
        addFriend(kefuFriendList, kefu, user);
        return user;
    }

    /**
     * @param friendList 好友列表
     * @param friend     好友
     * @description 通过好友，添加成为好友
     */
    private void addFriend(List<Friend> friendList, Account myAccount, Account friend) {
        for (Friend f : friendList) {
            if (f.getFriendAccount().getId().longValue() == friend.getId().longValue()) {
                //表示已经是好友，跳过
                return;
            }
        }
        //表示不是好友，需添加成好友
        Friend contacts = new Friend();
        contacts.setAccount(myAccount);
        contacts.setFriendAccount(friend);
        contacts.setRemark(friend.getUsername());
        contacts = friendDao.save(contacts);
        friendList.add(contacts);
    }

    /**
     * @param account  用户信息
     * @param pageBean 分页
     * @return PageBean<Account>
     * @description 分页查询用户列表
     */
    public PageBean<Account> findList(Account account, PageBean<Account> pageBean) {
        ExampleMatcher withMatcher = ExampleMatcher.matching().withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains());
        withMatcher = withMatcher.withIgnorePaths("status", "sex", "chatStatus");
        Example<Account> example = Example.of(account, withMatcher);
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize(),new Sort(Sort.Direction.DESC,"createTime"));
        Page<Account> findAll = accountDao.findAll(example, pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }

    /**
     * @param account  用户信息
     * @param pageBean 分页
     * @return PageBean<Account>
     * @description 分页查询用户列表
     */
    public PageBean<Account> findSexList(Account account, PageBean<Account> pageBean) {
        List<Account> sexAccount = accountDao.findAllOppositeSexAccount(account.getSex());
        int size = sexAccount.size();
        double totalPage = Math.ceil(size * 1.0 / pageBean.getPageSize());
        int totalPage1 = (int) totalPage;
        pageBean.setContent(sexAccount);
        pageBean.setTotal(size);
        pageBean.setTotalPage(totalPage1);
        return pageBean;
    }

    /**
     * @param username 用户名
     * @param id       编辑者id
     * @return boolean
     * @description 判断用户名是否存在，添加和编辑均可判断
     */
    public boolean isExistUsername(String username, Long id) {
        Account account = accountDao.findByUsername(username);
        if (account != null) {
            //表示用户名存在，接下来判断是否是编辑用户的本身
            return account.getId().longValue() != id.longValue();
        }
        return false;
    }

    /**
     * @param id 用户id
     * @description 按照用户id删除
     */
    public void delete(Long id) {
        accountDao.deleteById(id);
    }

    /**
     * @return long
     * @description 返回用户总数
     */
    public long total() {
        return accountDao.count();
    }

    /**
     * @param pageBean 分页
     * @return PageBean<Account>
     * @description 分页查询用户列表
     */
    public PageBean<Account> findAdminList(PageBean<Account> pageBean) {
        List<Account> findAll = accountDao.findAll();
        pageBean.setContent(findAll);
        pageBean.setTotal(findAll.size());
        pageBean.setTotalPage(1);
        return pageBean;
    }
}
